import {handleActions as createReducer} from 'redux-actions'
import {load_todo_success,add_todo_success,remove_todo_success,
   modify_todo_success,filter_todo,clear_todo_completed_success,
  edit_todo_success,rename_todo_success} from '../actions/todo.actions'
//  接受指令进行处理
const initialState = {
  todos: [],
  filter: 'all'
}
export default createReducer({
  [load_todo_success] : (state, action) => ({
    ...state,todos: action.payload
  }),
  [add_todo_success] : (state, action) => ({
    ...state,todos: [...state.todos,action.payload]
  }),
  [remove_todo_success] : (state, action) => {
    let id = action.id
    let index = state.todos.findIndex(todo => todo.id === id)
    let todos = JSON.parse(JSON.stringify(state.todos))
    todos.splice(index, 1)
    return {...state,todos}
  },
  [modify_todo_success] : (state, action) => {
    console.log('modify_todo_success ')
    console.log(state)
    let id = action.payload.id
    let index = state.todos.findIndex(todo => todo.id === id)
    let todos = JSON.parse(JSON.stringify(state.todos))
    todos[index].isCompleted = action.payload.isCompleted
    console.log(todos)
    return {...state,todos}
  },
  [filter_todo] : (state, action) => {
    console.log(action.payload)
    return {
      ...state,
      filter: action.payload
    }
  },
  [clear_todo_completed_success] : (state, action) => {
    let todos = JSON.parse(JSON.stringify(state.todos))
    todos = todos.filter(todo=> !todo.isCompleted)
    return {
      ...state,
      todos
    }
  },
  [edit_todo_success] : (state, action) => {
    console.log('edit_todo_success ')
    console.log(state)
    let id = action.payload.id
    let index = state.todos.findIndex(todo => todo.id === id)
    let todos = JSON.parse(JSON.stringify(state.todos))
    todos[index].isEditing = action.payload.isEditing
    console.log(todos)
    return {...state,todos}
  },
  [rename_todo_success] : (state, action) => {
    console.log('edit_todo_success ')
    console.log(state)
    let id = action.payload.id
    let index = state.todos.findIndex(todo => todo.id === id)
    let todos = JSON.parse(JSON.stringify(state.todos))
    todos[index].isEditing = action.payload.isEditing
    todos[index].taskName = action.payload.taskName
    console.log(todos)
    return {...state,todos}
  }
},initialState)
 